import os.path
import platform
import shutil
import subprocess
import site
import argparse

parser = argparse.ArgumentParser(
        description='Auto nuitka',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )

parser.add_argument(
    '--out-path',
    required=False,
    type=str,
    help='nuitka output'
)
args = parser.parse_args()


SHELL_DIR=os.path.dirname(__file__)
PROJECT_DIR=os.path.dirname(SHELL_DIR)
print(f"PROJECT_DIR: {PROJECT_DIR}")

SRC_DIR=os.path.join(PROJECT_DIR, "src")

import sys
sys.path.insert(0, SRC_DIR)

OUT_DIR=args.out_path or os.path.join(PROJECT_DIR, "out")
AGENT_DIR=os.path.join(OUT_DIR, "agent.dist")
AGENT_FILENAME="agent.exe"
print(f"AGENT_DIR: {AGENT_DIR}")
print(f"PYTHONPATH: {sys.path}")

if platform.system() == "Windows":
    nuitka = "nuitka.bat"
else:
    nuitka = "nuitka"

p = subprocess.run(f"{nuitka} "
                     f"--standalone "
                     f"--follow-import-to=mnagent,k2ci_agent "
                     f"--include-data-files={os.path.join(SHELL_DIR, 'k2ci_agent_cfg.json')}=k2ci_agent_cfg.json "
                     # f"--include-data-dir={os.path.join(SHELL_DIR, 'allure-2.33.0')}=allure "
                     f"--nofollow-import-to=aiosqlite,alembic,apscheduler,sanic,loguru,sqlalchemy,uvloop,pydantic,"
                   f"pluggy,aiofile,httpx,blinker,psutil,sanic_ext,viztracer,aio_pika,aiohttp "
                     f"--output-dir={OUT_DIR} "
                     f"--output-filename={AGENT_FILENAME} "
                     f"--remove-output "
                     f"--show-modules "
                     f"--include-module=textwrap,zoneinfo,http.cookies,argparse,sqlite3,uuid,plistlib "
                   f"--include-package=packaging,jaraco,platformdirs "
                     f"{os.path.join(SHELL_DIR, 'agent.py')}".split(), cwd=SRC_DIR)

if p.returncode == 0:
    for site_packages_path in site.getsitepackages():
        for item in os.listdir(site_packages_path):
            item_abs_path = os.path.join(site_packages_path, item)
            if os.path.isdir(item_abs_path):
                if (not item.startswith("pip")
                    and not item.startswith("setuptools")
                    and not item.startswith("build")
                    and not item.startswith("nuitka")
                    and not item.startswith("zstandard")
                    and not item.startswith("aiohttp")
                ):
                    shutil.copytree(item_abs_path, os.path.join(AGENT_DIR, item))
                    print(f"cp -r {item_abs_path} -t {os.path.join(AGENT_DIR, item)}")
            else:
                shutil.copyfile(item_abs_path, os.path.join(AGENT_DIR, item))
                print(f"cp {item_abs_path} -t {os.path.join(AGENT_DIR, item)}")

exit(p.returncode)
